<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天文件上传测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #34495e;
        }
        input[type="text"], textarea, input[type="file"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        input[type="file"] {
            background-color: #f8f9fa;
        }
        button {
            background-color: #3498db;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            width: 100%;
            transition: background-color 0.3s;
        }
        button:hover:not(:disabled) {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            display: none;
        }
        .status.info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .status.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .status.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .file-info {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 10px;
            margin: 10px 0;
            border-radius: 6px;
            font-family: monospace;
            font-size: 12px;
        }
        .chat-response {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 20px;
            margin-top: 20px;
            border-radius: 6px;
            max-height: 400px;
            overflow-y: auto;
        }
        .event-log {
            margin: 5px 0;
            padding: 8px;
            border-left: 4px solid #007bff;
            background-color: #f8f9fa;
            font-family: monospace;
            font-size: 12px;
        }
        .event-log.error {
            border-left-color: #dc3545;
            background-color: #f8d7da;
        }
        .event-log.success {
            border-left-color: #28a745;
            background-color: #d4edda;
        }
        .answer-chunk {
            background-color: #fff;
            border: 1px solid #dee2e6;
            padding: 15px;
            margin: 10px 0;
            border-radius: 6px;
            white-space: pre-wrap;
            line-height: 1.6;
        }
        .settings {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }
        @media (max-width: 600px) {
            .settings {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 聊天文件上传测试</h1>
        
        <form id="chatForm">
            <div class="form-group">
                <label for="question">问题：</label>
                <textarea id="question" name="question" placeholder="请输入您的问题..." required></textarea>
            </div>

            <div class="form-group">
                <label for="files">上传文件（可选，支持多个文件）：</label>
                <input type="file" id="files" name="files" multiple accept=".txt,.md,.html,.json,.xml,.csv,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.rtf">
                <small style="color: #666; margin-top: 5px; display: block;">
                    支持格式：txt, md, html, json, xml, csv, pdf, doc, docx, xls, xlsx, ppt, pptx, rtf
                </small>
            </div>

            <div class="form-group">
                <label for="userId">用户ID：</label>
                <input type="text" id="userId" name="userId" value="00000000-0000-0000-0000-000000000001" required>
            </div>

            <div class="settings">
                <div class="form-group">
                    <label for="useRAG">使用RAG：</label>
                    <select id="useRAG" name="useRAG">
                        <option value="true">是</option>
                        <option value="false">否</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="maxResults">最大结果数：</label>
                    <input type="number" id="maxResults" name="maxResults" value="5" min="1" max="20">
                </div>
            </div>

            <button type="submit" id="submitBtn">🚀 发送消息</button>
        </form>

        <div id="status" class="status"></div>
        
        <div id="response" class="chat-response" style="display: none;">
            <h3>📝 流式响应日志：</h3>
            <div id="eventLog"></div>
            
            <h3>💬 AI回答：</h3>
            <div id="answer" class="answer-chunk"></div>
        </div>
    </div>

    <script>
        const form = document.getElementById('chatForm');
        const submitBtn = document.getElementById('submitBtn');
        const status = document.getElementById('status');
        const response = document.getElementById('response');
        const eventLog = document.getElementById('eventLog');
        const answer = document.getElementById('answer');

        function showStatus(message, type = 'info') {
            status.textContent = message;
            status.className = `status ${type}`;
            status.style.display = 'block';
        }

        function logEvent(event, data, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.className = `event-log ${type}`;
            logEntry.innerHTML = `
                <strong>[${new Date().toLocaleTimeString()}] ${event}:</strong><br>
                ${typeof data === 'object' ? JSON.stringify(data, null, 2) : data}
            `;
            eventLog.appendChild(logEntry);
            eventLog.scrollTop = eventLog.scrollHeight;
        }

        function clearResponse() {
            eventLog.innerHTML = '';
            answer.textContent = '';
            response.style.display = 'none';
        }

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('question', document.getElementById('question').value);
            formData.append('userId', document.getElementById('userId').value);
            formData.append('useRAG', document.getElementById('useRAG').value);
            formData.append('maxResults', document.getElementById('maxResults').value);
            formData.append('similarityThreshold', '0.7');

            // 添加文件
            const files = document.getElementById('files').files;
            for (let i = 0; i < files.length; i++) {
                formData.append('files', files[i]);
            }

            submitBtn.disabled = true;
            submitBtn.textContent = '处理中...';
            clearResponse();
            
            showStatus(`正在发送请求... ${files.length > 0 ? `包含 ${files.length} 个文件` : '无文件'}`, 'info');
            response.style.display = 'block';

            try {
                const response = await fetch('/api/chat/ask-stream', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误：${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let answerBuffer = '';

                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('event:') || line.startsWith('data:')) {
                            if (line.startsWith('data:')) {
                                try {
                                    const eventData = JSON.parse(line.substring(5).trim());
                                    const eventType = lines[lines.indexOf(line) - 1]?.replace('event:', '').trim() || 'unknown';
                                    
                                    logEvent(eventType, eventData);

                                    if (eventType === 'answer_chunk') {
                                        answerBuffer += eventData.chunk;
                                        answer.textContent = answerBuffer;
                                    } else if (eventType === 'error') {
                                        logEvent('错误', eventData, 'error');
                                        showStatus('发生错误：' + eventData.error, 'error');
                                    } else if (eventType === 'complete') {
                                        logEvent('完成', eventData, 'success');
                                        showStatus('请求处理完成！', 'success');
                                    }
                                } catch (e) {
                                    // 忽略解析错误
                                }
                            }
                        }
                    }
                }

            } catch (error) {
                console.error('请求失败:', error);
                showStatus('请求失败：' + error.message, 'error');
                logEvent('请求错误', error.message, 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '🚀 发送消息';
            }
        });

        // 文件选择变化时显示文件信息
        document.getElementById('files').addEventListener('change', (e) => {
            const files = e.target.files;
            if (files.length > 0) {
                let fileInfo = `已选择 ${files.length} 个文件：\n`;
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    fileInfo += `${i + 1}. ${file.name} (${(file.size / 1024).toFixed(1)} KB)\n`;
                }
                showStatus(fileInfo, 'info');
            }
        });
    </script>
</body>
</html>
